// const mobilePhoneModel = require('../models/mobilePhone');
import mongoose from 'mongoose';
import UserModel from '../models/user';
// const sendSMSCode = require('../utils/sms');
import { md5 } from '../utils/share'
import { PROJECTION } from '../config/projection'

export function signupWx({ openid, unionid, roles }) {
  const newUser = new UserModel({
    openid,
    unionid,
    roles,
  })
  return newUser.save()
}

export function signup(pwd, phone, roles) {
  const newUser = new UserModel({
    password: md5(pwd),
    roles,
    phone,
  })
  return newUser.save()
}

export async function findById(id) {
  const user = await UserModel.findById(id).select('+roles +createdAt')
  return user
}

export async function findByOpenId(openid) {
  const user = await UserModel.findOne({ openid }).select('+roles +createdAt')
  return user
}

export async function findByPhone(phone) {
  const user = await UserModel.findOne({ phone }).select('+roles +createdAt')
  return user
}

export async function signin(phone, password) {
  const user = await UserModel.findOne({ phone }).select('password salt')
  if (!user || md5(password) !== user.password) {
    return {
      isSignin: false,
      user: null,
    }
  }
  return {
    isSignin: true,
    user: await findById(user._id),
  }
}

export async function updatePwd(phone, pwd) {
  const password = md5(pwd)
  const user = await UserModel.findOneAndUpdate({ phone }, { $set: { password } }, { returnDocument: 'after' })
  return user
}

/**
 * 更新用户信息
 * @param {String} phone 用户手机号
 * @param {Object} updateInfo 需要更新的信息
 */
export async function updateUser(_id, updateOpt) {
  delete updateOpt.password
  delete updateOpt.id
  await UserModel.updateOne({ _id }, updateOpt); // 更新用户信息
  const ret = await UserModel.findById({ _id }, PROJECTION.user); // 查询用户信息并返回所需数据
  return ret;
}
